package com.kaiyi.diannao.net;

import com.kaiyidiannao.data.DataCenter;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpResponseHandler;

/**
 * 数据解析分析
 *
 * @author kTian
 *
 */
public class AsyncHttpResponseParse extends AsyncHttpResponseHandler {
	
	private Context mContext;
	private LoadDataHandler mHandler;
	
	public AsyncHttpResponseParse(Context context, LoadDataHandler handler) {
		mContext = context;
		mHandler = handler;
	}

	@Override
	public void onStart() {
		super.onStart();
		mHandler.onStart();
	}

	@Override
	public void onFailure(Throwable error, String content) {
		super.onFailure(error, content);
		mHandler.onFailure(error, content);
	}

	@Override
	public void onSuccess(String content) {
		super.onSuccess(content);
		Log.i("log_ktian", "返回："+content);
		if( content!=null && content.length()>0 ) {
			try {
				JSONObject jsonObject = new JSONObject(content);
				if("1".equals(jsonObject.getString("code"))) {
					String json = jsonObject.getString("data");
                    DataCenter.msg = jsonObject.getString("msg");
                    if(json!=null && json.length()>0) {
						mHandler.onSuccess(json);
					}else{
						mHandler.onFailure();
						Toast.makeText(mContext, "请求失败, 请重试", Toast.LENGTH_SHORT).show();
					}
				}else{
                    DataCenter.msg = jsonObject.getString("msg");
					mHandler.onFailure(jsonObject.getString("msg"));
//					Toast.makeText(mContext, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                }
			} catch (JSONException e) {
				e.printStackTrace();
				mHandler.onFailure();
				Toast.makeText(mContext, "请求失败, 请重试", Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	@Override
	public void onFinish() {
		super.onFinish();
		mHandler.onFinish();
	}
	
}
